import React, { Component, Fragment } from 'react';
import { View,Button,OpenData,Image,Text,CoverImage} from '@tarojs/components';
import ListItem from './components/ListItem';
import { NavbarInfo } from '@/utils/navBarinfo';
import AvGroup from '../../components/avGroup/index';
import Taro from '@tarojs/taro';
import { AtIcon } from 'taro-ui'
import './home.less';


interface state{
      userInfo:{[Key:string]:any}
      hasUserInfo:Boolean
      canIUseGetUserProfile:Boolean
      navbarinfo:{[Key:string]:any}
      pennelStyle:{[Key:string]:any}
      listData:[any?]
}
export default class Home extends Component {
  constructor(props){
       super(props);
  }
  onPullDownRefresh (){
    this.getListData();
  }
  sysinfo:{[propKey:string]:any}=function(){
    try {
      return Taro.getSystemInfoSync()
    } catch (error) {
      return {}
    }
  
  }()
  state:state={
    userInfo: {},
    hasUserInfo: false,
    canIUseGetUserProfile: false,
    navbarinfo:{},
    pennelStyle:{
      top:0,
      display:"none"
    },
    listData:[]

  }
  startGetTopoDataInterval:any=null //计时器
  eventData={
    startTime:0,
    endTime:0,
    x:0,
    y:0,
    endX:0,
    endY:0,
    show:true
  }
  getUserProfile(e) {
    // 推荐使用wx.getUserProfile获取用户信息，开发者每次通过该接口获取用户个人信息均需用户确认
    // 开发者妥善保管用户快速填写的头像昵称，避免重复弹窗
    wx.getUserProfile({
      desc: '用于完善会员资料', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
      success: (res) => {
        console.log(res);
        this.setState({
          userInfo: res.userInfo,
          hasUserInfo: true

        })
      }
    })

    

  }
  getUserInfo=(e)=>{
    // 不推荐使用getUserInfo获取用户信息，预计自2021年4月13日起，getUserInfo将不再弹出弹窗，并直接返回匿名的用户个人信息
    this.setState({
      userInfo: e.detail.userInfo,
      hasUserInfo: true
    })
  }

 componentWillMount () {
    if (wx.getUserProfile) {
        this.setState({
          canIUseGetUserProfile: true
        })
    }

    NavbarInfo().then(res=>{
        this.setState({
          navbarinfo:res
        })
    })

    /**获取列表数据 */
    this.getListData();
  
  }
 async getListData(){
  Taro.showNavigationBarLoading();
   let resList = await Taro.request({
      url: 'http://api.mn-php.top/wap/message/list?u=2&r=%2FchatList', //仅为示例，并非真实的接口地址
      header: {
        'content-type': 'application/json' // 默认值
      },
      method:"POST",
      data:{
        pageNow: 1,
        pageSize: 15,
        params: {}
      }
   
      });
  
    this.setState({
      listData:resList.data.data.list
    }) 
    Taro.hideNavigationBarLoading();
    Taro.stopPullDownRefresh();

  }
  removeMsg(type:string){
    console.log("关闭面板")
    this.setState({
      pennelStyle:{
       display:"none"
      }
    })
    Taro.vibrateShort();
   
  }
  /**列表长按 */
  tapStart(id,idx,e){
    this.eventData.show=true
    this.eventData.startTime=e.timeStamp;
    this.eventData.x=e.changedTouches[0].clientX;
    this.eventData.y=e.changedTouches[0].clientY;
    this.startGetTopoDataInterval&&clearTimeout(this.startGetTopoDataInterval);
    this.startGetTopoDataInterval = setTimeout(()=>{
          if(!this.eventData.show) return;
          this.setState({
            pennelStyle:{
               top:e.changedTouches[0].clientY,
               left:e.changedTouches[0].clientX,
               display:"block",
            }
          })
           try {
            setTimeout(() => {
              const query = wx.createSelectorQuery()
              query.select('.pennel').fields({
                rect:true
              })
              query.exec((res)=>{
                 if(res[0].right>this.sysinfo.windowWidth){
                    this.setState({
                      pennelStyle:{
                        left:this.sysinfo.windowWidth-res[0].width,
                        top:e.changedTouches[0].clientY,
                        display:"block"
                      }
                    })
                 };
                
              })
            });
          } catch (error) {
            
          }
          Taro.vibrateShort({
            type:"heavy"
          });
          // Taro.vibrateLong();
          clearTimeout(this.startGetTopoDataInterval);
          this.eventData.startTime=0;
          this.startGetTopoDataInterval=null;
          console.log(id,"选中的ID")
    },800);
  }
  move(e){
    // console.log(e)
    // console.log(e.changedTouches[0].clientY,e.changedTouches[0].clientX);
    let diffx = Math.abs(e.changedTouches[0].clientY-this.eventData.y);
    let diffy = Math.abs(e.changedTouches[0].clientX-this.eventData.x)
    if(diffx>15||diffy>15){
      this.eventData.show=false
      console.log("0")
    }
  }
  tapEnd(e){
    this.eventData.endTime=e.timeStamp;
    this.tapCallback(this.eventData.endTime-this.eventData.startTime);
  }
  tapCallback(diff){
    if(diff<=800){
       clearTimeout(this.startGetTopoDataInterval);      
    }
  }
   /**列表长按 end */
   actionClick(item){
     console.log(item)
      Taro.navigateTo({
        url:`../actionMsg/index?id=${item.id}&name=${item.gName}&gType=${item.gType}`,
      })

   }
  componentDidMount () {}
  componentWillUnmount () {}
  componentDidShow () {
    this.getListData();
  }
  componentDidHide () {} 
  render () {
    let data = this.state;
    return (
           <Fragment>
            <View className="listBox"> 
              {
                data.listData.map((item,index)=>{
                  if(item.lastMsg){
                    return <ListItem key={item.id} data={{index:index,len:3,item:item}}  onClick={this.actionClick.bind(this,item)}  ontouchstart={this.tapStart.bind(this,item.id,index)} touchmove={this.move.bind(this)}  ontouchEnd={this.tapEnd.bind(this)}></ListItem>
                  }
                  
                })
              }
            </View>
            <View catchMove={true} className="pennel" style={data.pennelStyle}>
                <View className="option" onClick={this.removeMsg.bind(this,'remove')}><AtIcon value='trash' size='20' color='#F00'></AtIcon>删除</View>
                <View className="option" onClick={this.removeMsg.bind(this,'up')}><AtIcon value='bookmark' size='20' color='#6467f0'></AtIcon>置顶</View>
                <View className="option" onClick={this.removeMsg.bind(this,'ignore')}><AtIcon value='blocked' size='18' color='#606266'></AtIcon>忽略</View>
            </View>
            <View className="mask" onTouchStart={()=>{this.setState({pennelStyle:{display:"none"}})}} style={{display:data.pennelStyle.display}}>
            </View>
            </Fragment>
    )
  }
}
